<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/6/27 10:25
 * Modified Time: 2019/6/27 10:25
 * Version: 2.0
 */

namespace App\Modules\Service\Repositories;


use App\Exceptions\NotFoundException;
use App\Models\Service;
use App\Modules\Service\Criterias\BarberRoyaltySetCriteria;
use App\Modules\Service\Validators\ServiceValidator;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Flower\Core\Repository\Exceptions\ValidatorException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\MessageBag;

class ServiceRepository extends BaseRepository
{
    /**
     * 新增服务
     */
    public function createService($store_id, $name, $price, $type, $royalty, $cost,$assistant_royalty)
    {
        $data = [
            'store_id' => $store_id,
            'name' => $name,
            'price' => $price,
            'type' => $type,
            'royalty' => $royalty,
            'cost' => $cost,
            'assistant_royalty' => $assistant_royalty
        ];
        $new_service = $this->create($data);
        return $new_service;
    }

    public function model()
    {
        return Service::class;
    }

    public function validator()
    {
        return ServiceValidator::class;
    }


    /**
     * 依据$id 检测服务是否存在
     * @param $id
     * @return mixed
     * @throws NotFoundException
     */
    public function isExisted($id, $isBool = false)
    {
        $service = $this->find($id);
        if (empty($service)) {
            if ($isBool) {
                return false;
            } else {
                throw new NotFoundException(['msg' => '服务不存在']);
            }
        }
        return $service;
    }

    public function findPrice($id)
    {
        return $this->find($id);
    }


    public function getBarberRoyaltySet($storeId, $userId)
    {
        return $this->pushCriteria(new BarberRoyaltySetCriteria($storeId, $userId))->get();
    }

    /**获取数组形式店铺服务
     * @param $store_id
     * @return mixed
     */
    public function getStoreServiceArray($store_id)
    {
        return $this->findByField(['store_id' => $store_id])->toArray();
    }


    public function getOrderServiceAmountCount($storeId, $startDate, $endDate, $isAmount = 1, $isLimit = 1, $isProfit = 0)
    {
        $price = $isProfit ? 'profit' : 'real_price';
        $sql_is_amount = $isAmount ? 'sum(o.' . $price . ') AS counts' : 'count(o.id) AS counts';
        $sql_is_limit = $isLimit ? 'limit 5' : '';
        $sql = 'select b.id as service_id, b.type, b.name as service_name, p.image, (case when counts is null then 0 else counts end) as counts from (SELECT s.id,s.name,s.type,  ' . $sql_is_amount . ' FROM hx_store_service AS s LEFT JOIN hx_order_item AS i ON i.service_id = s.id LEFT JOIN hx_order AS o ON o.id = i.order_id AND FROM_UNIXTIME(o.finish_time, \'%Y-%m-%d\') <= "' . $startDate . '" AND FROM_UNIXTIME(o.finish_time, \'%Y-%m-%d\') >= "' . $endDate . '" WHERE	s.store_id = "' . $storeId . '"  AND deleted_at IS NULL GROUP BY s.id ORDER BY counts DESC   ' . $sql_is_limit . ' ) as b LEFT JOIN hx_dictionary_item  as d ON d.id =b.type and d.parent_id=4 LEFT JOIN hx_picture as p ON d.resource = p.id';

        return DB::select($sql);

    }

    public function getBarberOrderServiceAmountCount($storeId, $startDate, $endDate, $isAmount = 1, $isLimit = 1, $user_id)
    {

        $sql_is_amount = $isAmount ? 'sum(o.real_price) AS counts' : 'count(o.id) AS counts';
        $sql_is_limit = $isLimit ? 'limit 5' : '';
        $sql = 'select b.id as service_id, b.type, b.name as service_name, p.image, (case when counts is null then 0 else counts end) as counts from (SELECT s.id,s.name,s.type,  ' . $sql_is_amount . ' FROM hx_store_service AS s LEFT JOIN hx_order_item AS i ON i.service_id = s.id LEFT JOIN hx_order AS o ON o.id = i.order_id AND FROM_UNIXTIME(o.finish_time, \'%Y-%m-%d\') <= "' . $startDate . '" AND FROM_UNIXTIME(o.finish_time, \'%Y-%m-%d\') >= "' . $endDate . '" WHERE	o.store_id = "' . $storeId . '"  AND deleted_at IS NULL AND o.barber_id ="' . $user_id . '" GROUP BY s.id ORDER BY counts DESC   ' . $sql_is_limit . ' ) as b LEFT JOIN hx_dictionary_item  as d ON d.id =b.type and d.parent_id=4 LEFT JOIN hx_picture as p ON d.resource = p.id';

        return DB::select($sql);

    }


    /**
     * 获取店铺服务数量
     * @param $store_id
     * @return mixed
     */
    public function getStoreServiceCount($store_id)
    {
        return $this->model->where('store_id', $store_id)->get()->count();
    }

    /**
     * 编辑服务
     * @param $service_id
     * @param $name
     * @param $price
     * @param $type
     * @param $royalty
     * @return mixed
     * @throws NotFoundException
     */
    public function editService($service_id, $name, $price, $type, $royalty ,$cost,$assistant_royalty)
    {
        $this->isExisted($service_id);
        $data = [];

        if ($name) {
            $data['name'] = $name;
        }
        if ($price) {
            $data['price'] = $price;
        }
        if ($type) {
            $data['type'] = $type;
        }
        if ($royalty) {
            $data['royalty'] = $royalty;
        }
        if ($cost) {
            $data['cost'] = $cost;
        }
        if($assistant_royalty){
        	$data['assistant_royalty'] = $assistant_royalty;
        }

        return $this->update($data, $service_id);
    }


	/**
	 * 删除服务
	 * @param $service_id
	 * @return int
	 * @throws NotFoundException
	 */
    public function delService($service_id)
    {
        $this->isExisted($service_id);

        return $this->delete($service_id);
    }

	/**
	 * 查找服务列表信息(根据ids)
	 * @param $ids
	 * @return mixed
	 */
    public function getServiceListByIds($ids){
    	return $this->model->whereIn('id',$ids)->select();
    }
}
